package com.turing.usdtpay.http.okhttp.builder;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public abstract class RequestBuilder {

    protected String url;
    protected Map<String, String> params;
    protected Object tag;

    protected OkHttpClient mOkHttpClient;

    public RequestBuilder(OkHttpClient okHttpClient) {
        this.mOkHttpClient = okHttpClient;
    }

    abstract Call enqueue(Callback callback);

    abstract Response execute() throws IOException;

    protected void appendHeaders(Request.Builder builder, Map<String, String> headers) {
        Headers.Builder headerBuilder = new Headers.Builder();
        if (headers == null || headers.isEmpty()) return;

        for (String key : headers.keySet()) {
            headerBuilder.add(key, headers.get(key));
        }
        builder.headers(headerBuilder.build());
    }

    protected void appendParams(FormBody.Builder builder, Map<String, String> params) {

        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
    }

    protected String appendParams(String url, Map<String, String> params) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append(url + "?");
            if (params != null && !params.isEmpty()) {
                for (String key : params.keySet()) {
                    //URL ENCODE UTF-8
                    String value = params.get(key);
                    String urlValue = URLEncoder.encode(value, "UTF-8");
                    sb.append(key).append("=").append(urlValue).append("&");
                }
            }

            sb = sb.deleteCharAt(sb.length() - 1);
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return url;
        }
    }

}
